import React from 'react'
import F from 'lodash/fp'
import {connect} from 'react-redux'
import {contentChange, cropperReady} from '../actions/content-change'
import Page from './card-page.jsx'
import Cropper from './cropper.jsx'

let cropper

class PhotoCropper extends React.Component {
    constructor(props) {
        super(props)
    }

    shouldComponentUpdate(nextProps) {
        return nextProps.isReady
    }

    render () {
        let {path} = this.props
        if (!path || path.length !== 1) return null
        path = path[0].split('.')
        let {getPhoto, getPreveiw, croped} = this.props
            , elm = $(`#card .page:eq(${path[0]}) .elm:eq(${path[1]})`)
            , widen = parseInt(elm.width())
            , photo = getPhoto()
            , src = photo ? photo.path + '/raw' : null
            , preview = getPreveiw(path[0])
            , ratio = widen/parseInt(elm.height())

        return (
            <div className="am-modal-dialog ">
                <div className="cut-img-modal-hd">
                    图片裁剪
                    <a href="javascript: void(0)" className="cut-img-modal-close" data-am-modal-close=""><i className="fa fa-close"></i></a>
                </div>
                <div className="cut-img-modal-bd" style={{maxHeight: '400px', maxWidth: '600px', minHeight: '400px', minWidth: '400px'}}>
                        <Cropper ratio={ratio} src={src} ready={c => cropper = c} />
                </div>
                <div className="cut-img-btn-wp">
                    <button className="cut-img-confirm" onClick={() => croped(photo.path, path, widen)}>确认</button>
                    <button className="cut-img-confirm cut-img-quit" data-am-modal-close="">取消</button>
                </div>
            </div>
        )
    }
}

module.exports = connect(
    ({global, card, gallery}) => ({
        getPhoto: () => F.find(['id', gallery.selectedId], gallery.photos),
        path: card.selectedPath,
        getPreveiw: (p) => F.cloneDeep(card.pages[p].elements),
        isReady: global.cropperReady
    })
    , (dispatch, props) => ({
        croped: (src, path, widen) => {
            let {x, y, width, height} = cropper.cropper('getData')
            console.log(x, y, width, height);
            [x, y, width, height] = [x, y, width, height].map(Math.ceil)
            const content = `<img src="${src}/${width}x${height}_${x}x${y}_${widen * 2}" />`
            props.$modal.modal('close')
            dispatch(contentChange(content, path))
        },
        cropperReady: F.compose(dispatch, cropperReady)
    })
)(PhotoCropper)